<!DOCTYPE html>
<html lang="zh-Hans">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.3.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/blog/images/logo.svg" color="#222">

<link rel="stylesheet" href="/blog/css/main.css">

<link rel="stylesheet" href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&display=swap&subset=latin,latin-ext">
<link rel="stylesheet" href="/blog/lib/font-awesome/css/font-awesome.min.css">


<script id="hexo-configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    hostname: new URL('https://guodh.gitee.io/blog').hostname,
    root: '/blog/',
    scheme: 'Pisces',
    version: '7.7.1',
    exturl: false,
    sidebar: {"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},
    copycode: {"enable":true,"show_result":true,"style":null},
    back2top: {"enable":true,"sidebar":false,"scrollpercent":false},
    bookmark: {"enable":false,"color":"#222","save":"auto"},
    fancybox: false,
    mediumzoom: false,
    lazyload: false,
    pangu: false,
    comments: {"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},
    algolia: {
      appID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    },
    localsearch: {"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},
    path: 'search.xml',
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}}
  };
</script>

  <meta name="description" content="这次的缘由也是群里的一个同学提到的：  dubbo的线程池为什么缺省值是100？  这里有两个问题：dubbo配置的这个线程池是管理的是短链接吗？那么在日常应用中线程池应该配置多大？ NIO配置可以看到thread和iothread是配置的不同的，那么这个让人想起一个比较简单的配置方法：   如果是CPU密集型应用，则线程池大小设置为N+1 如果是IO密集型应用，则线程池大小设置为2N+1   因">
<meta property="og:type" content="article">
<meta property="og:title" content="线程池调优">
<meta property="og:url" content="https://guodh.gitee.io/blog/2017/09/17/2017/%E7%BA%BF%E7%A8%8B%E6%B1%A0%E8%B0%83%E4%BC%98/index.html">
<meta property="og:site_name" content="蛋蛋的小屋">
<meta property="og:description" content="这次的缘由也是群里的一个同学提到的：  dubbo的线程池为什么缺省值是100？  这里有两个问题：dubbo配置的这个线程池是管理的是短链接吗？那么在日常应用中线程池应该配置多大？ NIO配置可以看到thread和iothread是配置的不同的，那么这个让人想起一个比较简单的配置方法：   如果是CPU密集型应用，则线程池大小设置为N+1 如果是IO密集型应用，则线程池大小设置为2N+1   因">
<meta property="og:locale">
<meta property="og:image" content="https://olwr1lamu.qnssl.com/dubboThread.png">
<meta property="og:image" content="https://olwr1lamu.qnssl.com/jiagou.png">
<meta property="article:published_time" content="2017-09-17T07:41:00.000Z">
<meta property="article:modified_time" content="2017-09-17T08:35:13.000Z">
<meta property="article:author" content="RunningEgg">
<meta property="article:tag" content="技术">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://olwr1lamu.qnssl.com/dubboThread.png">

<link rel="canonical" href="https://guodh.gitee.io/blog/2017/09/17/2017/%E7%BA%BF%E7%A8%8B%E6%B1%A0%E8%B0%83%E4%BC%98/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome: false,
    isPost: true
  };
</script>

  <title>线程池调优 | 蛋蛋的小屋</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-meta">

    <div>
      <a href="/blog/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">蛋蛋的小屋</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
        <p class="site-subtitle">来了就看看吧，没有刀剑只有故事</p>
  </div>

  <div class="site-nav-toggle">
    <div class="toggle" aria-label="Toggle navigation bar">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>
</div>


<nav class="site-nav">
  
  <ul id="menu" class="menu">
        <li class="menu-item menu-item-home">

    <a href="/blog/" rel="section"><i class="fa fa-fw fa-home"></i>Home</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/blog/about/" rel="section"><i class="fa fa-fw fa-user"></i>About</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/blog/archives/" rel="section"><i class="fa fa-fw fa-archive"></i>Archives</a>

  </li>
        <li class="menu-item menu-item-book">

    <a href="/blog/book/" rel="section"><i class="fa fa-fw fa-archive"></i>book</a>

  </li>
  </ul>

</nav>
</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content">
            

  <div class="posts-expand">
      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block " lang="zh-Hans">
    <link itemprop="mainEntityOfPage" href="https://guodh.gitee.io/blog/2017/09/17/2017/%E7%BA%BF%E7%A8%8B%E6%B1%A0%E8%B0%83%E4%BC%98/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/blog/images/avatar.gif">
      <meta itemprop="name" content="RunningEgg">
      <meta itemprop="description" content="写下我的点点滴滴，写下我对这个世界的看法，还有我内心锁崇拜的技术">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="蛋蛋的小屋">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          线程池调优
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">Posted on</span>
              

              <time title="Created: 2017-09-17 15:41:00 / Modified: 16:35:13" itemprop="dateCreated datePublished" datetime="2017-09-17T15:41:00+08:00">2017-09-17</time>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <p>这次的缘由也是群里的一个同学提到的：</p>
<blockquote>
<p>dubbo的线程池为什么缺省值是100？</p>
</blockquote>
<p>这里有两个问题：dubbo配置的这个线程池是管理的是短链接吗？那么在日常应用中线程池应该配置多大？<br><img src="https://olwr1lamu.qnssl.com/dubboThread.png" width="100%" height="100%" alt="dubbo默认配置"/></p>
<h2 id="NIO配置"><a href="#NIO配置" class="headerlink" title="NIO配置"></a>NIO配置</h2><p>可以看到thread和iothread是配置的不同的，那么这个让人想起一个比较简单的配置方法：</p>
<blockquote>
<ul>
<li>如果是CPU密集型应用，则线程池大小设置为N+1</li>
<li>如果是IO密集型应用，则线程池大小设置为2N+1</li>
</ul>
</blockquote>
<p>因为IO秘籍型CPU使用较少，是否可以这么理解，在使用NIO结构的时候，Acceptor可以值配置2N+1个或者较少的线程，而实际处理业务的场景的配置1个或者较多的线程，NIO示例如下图。<br><img src="https://olwr1lamu.qnssl.com/jiagou.png" width="100%" height="100%" alt="结构图"/></p>
<h2 id="dubbo线程池为什么可以配置100"><a href="#dubbo线程池为什么可以配置100" class="headerlink" title="dubbo线程池为什么可以配置100"></a>dubbo线程池为什么可以配置100</h2><p>学习dubbo官方文档可知：Dubbo协议缺省每服务每提供者每消费者使用单一长连接，如果数据量较大，可以使用多个连接。这个是典型的NIO模式。</p>
<blockquote>
<p>引用：作者微子Lee<br>链接：<a href="http://www.jianshu.com/p/32edaf9736a2">http://www.jianshu.com/p/32edaf9736a2</a></p>
</blockquote>
<blockquote>
<p>缺省协议，使用基于mina1.1.7+hessian3.2.1的tbremoting交互。<br>连接个数：单连接<br>连接方式：长连接<br>传输协议：TCP<br>传输方式：NIO异步传输<br>序列化：Hessian二进制序列化<br>适用范围：传入传出参数数据包较小（建议小于100K），消费者比提供者个数多，单一消费者无法压满提供者，尽量不要用dubbo协议传输大文件或超大字符串。<br>适用场景：常规远程服务方法调用</p>
</blockquote>
<h2 id="NIO的线程池大小是否会影响上下文切换"><a href="#NIO的线程池大小是否会影响上下文切换" class="headerlink" title="NIO的线程池大小是否会影响上下文切换"></a>NIO的线程池大小是否会影响上下文切换</h2><p>本质是IO的操作是不需要消耗CPU资源的。</p>
<blockquote>
<p>引用：作者王晓远<br>链接：<a href="https://www.zhihu.com/question/31259327/answer/147547667">https://www.zhihu.com/question/31259327/answer/147547667</a></p>
</blockquote>
<blockquote>
<p>DMA(Direct Memory Access), 直接存储器访问为什么不经过CPU？<br>I/O发展是经过一下一步步发展的</p>
<ol>
<li>CPU直接控制外围设备(硬盘磁带等), 在简单微处理器中常用</li>
<li>增加I/O模块, 将CPU与外围设备解耦, CPU只与I/O模块打交道. 只需定义好接口, CPU厂商和外围设备厂商就可以相互根据接口开发, 互不影响</li>
<li>增加中断方式, 还是经过I/O模块, 只不过I/O模块完成之后, 只需通知CPU即可, CPU在等待阶段完全可以去做其他事情, 提高CPU利用率.</li>
<li>I/O模块增加DMA控制器. 之前的阶段是每次只传输一个字, 就通知CPU, 就发起一次中断, CPU放到寄存器中, 再放到内存中. 这样CPU就会被连续的中断打断, 不断切换进程, 上下文, 效率很低.DMA控制器类似于一个小的CPU, 有自己的寄存器(记录主存地址和取到的字的count等). CPU可以发起一个DMA请求, 传入读写操作类型, 相关I/O设备地址, 内存的起始地址, 要操作的字数.然后DMA就可以获取总线的控制权, 将一大块内存和外部I/O读入或写出.等操作完成后, 再通知CPU. 释放总线控制权.</li>
</ol>
</blockquote>
<p>顺便说个，如果是Netty的handler中需要处理耗时任务，应该自己开启线程去处理，这个在业务中需要处理。</p>
<h2 id="CPU如何分配资源到多个线程池"><a href="#CPU如何分配资源到多个线程池" class="headerlink" title="CPU如何分配资源到多个线程池"></a>CPU如何分配资源到多个线程池</h2><p>笔者猜测应该是（例如Linux内核）决定如何去处理这些事情，每个单独的线程应该都是操作系统去管理调度那个CPU。</p>
<blockquote>
<p>引用：作者vczh<br>链接：<a href="https://www.zhihu.com/question/27406575/answer/149186136">https://www.zhihu.com/question/27406575/answer/149186136</a></p>
</blockquote>
<blockquote>
<p>CPU通常提供了一个framework，让操作系统利用中断来实现线程调度，在线程调度里实现锁。操作系统的线程并不是非要运行在某一个固定的逻辑核上面，而且线程通常绑定了一组寄存器的值（如果像VC++一样用__await实现coroutine的话，会有若干组）。所以基本的关系就是，CPU有物理核，上面再有逻辑核，操作系统通过把寄存器的值（和一些其他的东西）在不同的时候复制到不同的逻辑核上面来实现线程。</p>
</blockquote>
<p>还记得公司的架构师抽抽大神给我们的分享，如果上下文切换太过于频繁，可以通过将一个进程直接绑定在一个CPU上，这样反而能够提升效率。<br>可以通过Linux下的一个工具，taskset，将一个进程绑到CPU上。</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">taskset [options] [mask | cpu-list] [pid|cmd [args...]]</span><br></pre></td></tr></table></figure>
<p>或者是利用国外的这个<a href="https://github.com/OpenHFT/Java-Thread-Affinity%E3%80%82">https://github.com/OpenHFT/Java-Thread-Affinity。</a><br>将进程绑定到CPU上，作为一个业务开发，可能实际应用场景不多，有兴趣的同学可以看看。</p>

    </div>

    
    
    

      <footer class="post-footer">
          <div class="post-tags">
              <a href="/blog/tags/%E6%8A%80%E6%9C%AF/" rel="tag"># 技术</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/blog/2017/08/13/2017/MQ%E7%9A%84Producer%E7%90%86%E8%A7%A3/" rel="prev" title="MQ的Producer理解">
      <i class="fa fa-chevron-left"></i> MQ的Producer理解
    </a></div>
      <div class="post-nav-item">
    <a href="/blog/2017/09/21/2017/cobar-drive%E7%90%86%E8%A7%A3/" rel="next" title="Cobar-Drive理解">
      Cobar-Drive理解 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  

  </div>


          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let activeClass = CONFIG.comments.activeClass;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          Table of Contents
        </li>
        <li class="sidebar-nav-overview">
          Overview
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#NIO%E9%85%8D%E7%BD%AE"><span class="nav-number">1.</span> <span class="nav-text">NIO配置</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#dubbo%E7%BA%BF%E7%A8%8B%E6%B1%A0%E4%B8%BA%E4%BB%80%E4%B9%88%E5%8F%AF%E4%BB%A5%E9%85%8D%E7%BD%AE100"><span class="nav-number">2.</span> <span class="nav-text">dubbo线程池为什么可以配置100</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#NIO%E7%9A%84%E7%BA%BF%E7%A8%8B%E6%B1%A0%E5%A4%A7%E5%B0%8F%E6%98%AF%E5%90%A6%E4%BC%9A%E5%BD%B1%E5%93%8D%E4%B8%8A%E4%B8%8B%E6%96%87%E5%88%87%E6%8D%A2"><span class="nav-number">3.</span> <span class="nav-text">NIO的线程池大小是否会影响上下文切换</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#CPU%E5%A6%82%E4%BD%95%E5%88%86%E9%85%8D%E8%B5%84%E6%BA%90%E5%88%B0%E5%A4%9A%E4%B8%AA%E7%BA%BF%E7%A8%8B%E6%B1%A0"><span class="nav-number">4.</span> <span class="nav-text">CPU如何分配资源到多个线程池</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">RunningEgg</p>
  <div class="site-description" itemprop="description">写下我的点点滴滴，写下我对这个世界的看法，还有我内心锁崇拜的技术</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/blog/archives/">
        
          <span class="site-state-item-count">89</span>
          <span class="site-state-item-name">posts</span>
        </a>
      </div>
      <div class="site-state-item site-state-tags">
        <span class="site-state-item-count">24</span>
        <span class="site-state-item-name">tags</span>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="mailto:guodh_1@163.com" title="E-Mail → mailto:guodh_1@163.com" rel="noopener" target="_blank"><i class="fa fa-fw fa-envelope"></i>E-Mail</a>
      </span>
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">RunningEgg</span>
</div>
  <div class="powered-by">Powered by <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> v5.3.0
  </div>
  <span class="post-meta-divider">|</span>
  <div class="theme-info">Theme – <a href="https://pisces.theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Pisces</a> v7.7.1
  </div>

        








      </div>
    </footer>
  </div>

  
  <script src="/blog/lib/anime.min.js"></script>
  <script src="/blog/lib/velocity/velocity.min.js"></script>
  <script src="/blog/lib/velocity/velocity.ui.min.js"></script>

<script src="/blog/js/utils.js"></script>

<script src="/blog/js/motion.js"></script>


<script src="/blog/js/schemes/pisces.js"></script>


<script src="/blog/js/next-boot.js"></script>




  















  

  

</body>
</html>
